package com.jsyso.weixin.api;

import java.io.File;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jsyso.jsyso.util.AbsHandler;
import com.jsyso.weixin.utils.Fail;
import com.jsyso.weixin.utils.HttpUtils;
import com.jsyso.weixin.utils.Params;
import com.jsyso.weixin.utils.Success;

/**
 * API基类
 * @author janjan, xujian_jason@163.com
 *
 */
public abstract class API {
	protected Logger logger = LoggerFactory.getLogger(getClass());
	protected static final String API_WEIXIN_QQ_COM = "https://api.weixin.qq.com";
	protected static final String API_MCH_WEIXIN_QQ_COM = "https://api.mch.weixin.qq.com";
	protected static final String MP_WEIXIN_QQ_COM = "https://mp.weixin.qq.com";
	protected static final String OPEN_WEIXIN_QQ_COM = "https://open.weixin.qq.com";
	
	protected String url;								// 请求url
	protected Params getParams;							// get参数
	protected String postData;							// post数据
	protected File file;								// upload上传文件
	protected RequestMethod method = RequestMethod.GET;	// 请求方法（默认GET请求）
	
	protected Response cacheResponse;					// 缓存的Response（如有缓存数据则不发起HTTP请求）
	protected ResponseType responseType = ResponseType.JSON; // 响应数据类型
	protected AbsHandler<Response> successHandle;		// 请求成功需要回调处理
	
	public static <T extends API> T create(Class<T> clazz) {
		T t = null;
		try {
			t = clazz.newInstance();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return t;
	}
	
	public void get(Success success) {
		request(success, null);
	}
	
	public void get(Success success, Fail fail) {
		request(success, fail);
	}
	
	public Response get() {
		return request(null, null);
	}
	
	public Response request(Success success, Fail fail) {
		Throwable cause = null;
		Response response = cacheResponse;
		try {
			if(response == null && StringUtils.isNotBlank(url)) {
				if(logger.isDebugEnabled()) {
					logger.debug("[请求微信服务器]url="+url);
				}
				if(method == RequestMethod.GET) {
					response = new Response(HttpUtils.getInstance().get(url, getParams.getData()), responseType);
				}
				else if(method == RequestMethod.POST) {
					response = new Response(HttpUtils.getInstance().post(url, postData), responseType);
				}
				else if(method == RequestMethod.UPLOAD) {
					response = new Response(HttpUtils.getInstance().upload(url, file, postData), responseType);
				}
				if(logger.isDebugEnabled()) {
					logger.debug("[返回内容]response="+(response == null ? "空内容" : response.getAttrs()));
				}
			}
		} catch (Exception e) {
			cause = e;
		} finally {
			int errcode = response == null ? -1 : response.errcode();
			if(errcode == 0) {
				// 先处理内部回调
				if(successHandle != null)
					successHandle.doHandle(response);;
				// 处理外部success回调
				if(success != null)
					success.onSuccess(response.getAttrs(), response.getContent());
			}else if(fail != null){
				String errmsg = response == null ? "系统异常，请重试" : response.errmsg();
				fail.onFail(errcode, errmsg, cause);
			}
		}
		return response;
	}
	
}
